<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>菜单管理</title>
    <link rel="stylesheet" href="/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <style>
        .layui-btn:not(.layui-btn-lg ):not(.layui-btn-sm):not(.layui-btn-xs) {
            height: 34px;
            line-height: 34px;
            padding: 0 8px;
        }
    </style>
</head>
<body>
<script type="text/html" id="toolBar">
    <div class="layui-btn-group">
        <a class="layui-btn layui-btn-sm layui-btn data-count-add" lay-event="add">添加</a>
    </div>
</script>
<div class="layuimini-container">
    <div class="layuimini-main">
        <table id="menu-table" class="layui-table" lay-filter="menu-table"></table>
    </div>
</div>

<script type="text/html" id="enableTpl">
    <input type="checkbox" name="enable" value="{{d.id}}" lay-skin="switch" lay-text="是|否" lay-filter="enableSwitch" {{ d.enable == 1 ? 'checked' : '' }}>
</script>

<!-- 操作列 -->
<script type="text/html" id="auth-state">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!--添加和修改的弹出层开始-->
<div id="addOrUpdateDiv" style="display: none;padding: 0.3125rem">
    <form method="post" class="layui-form layui-form-pane" lay-filter="dataFrm" id="dataFrm">
        <div class="layui-form-item" id="div_pid">
            <label class="layui-form-label">菜单类型</label>
            <div class="layui-input-block">
                <input type="radio" name="type" lay-filter="typeFilter" value="leftmenu" title="左侧菜单" checked="">
                <input type="radio" name="type" lay-filter="typeFilter" value="topmenu" title="顶部菜单" >
            </div>
         </div>
        <div class="layui-form-item item_leftmenu item_permission">
            <div class="p-container">
                <label class="layui-form-label">父级菜单</label>
                <div class="layui-input-inline">
                   <input type="hidden" name="id" id="id" />
                   <input type="hidden" name="pid" id="p_id" />
                   <input type="text" name="pid_name" id="p_name" readonly="readonly" autocomplete="off" placeholder="请选择父级菜单" class="layui-input">
                </div>
                <div class="layui-input-inline" id="selectPid">
                   <a class="layui-btn layui-btn-warm" id="doSelectMenu"><label class="layui-icon layui-icon-male"></label>选择</a>
                </div>
            </div>
         </div>
         <div class="layui-form-item ">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
               <input type="hidden" name="id" />
              <input type="text" name="title" lay-verify="required" autocomplete="off" placeholder="请输入菜单名称" class="layui-input">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">编码</label>
            <div class="layui-input-block">
              <input type="text" name="typeCode"  autocomplete="off" placeholder="请输入菜单编码" class="layui-input">
            </div>
           </div>
           <div class="layui-form-item item_topmenu  item_leftmenu">
                <label class="layui-form-label">图标</label>
                <div class="layui-input-block">
                  <input type="text" name="icon"  autocomplete="off" placeholder="请输入菜单图标" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item  item_leftmenu">
                    <label class="layui-form-label">链接地址</label>
                    <div class="layui-input-block">
                      <input type="text" name="href"  autocomplete="off" placeholder="请输入菜单链接地址" class="layui-input">
                    </div>
             </div>
            <div class="layui-form-item item_leftmenu">
                    <label class="layui-form-label">TARGET</label>
                    <div class="layui-input-block">
                            <input type="radio" name="target" value="_self" title="_self" checked="" >
                            <input type="radio" name="target" value="_blank" title="_blank" >
                    </div>
             </div>
              <div class="layui-form-item">
                      <label class="layui-form-label">排序码</label>
                      <div class="layui-input-block">
                        <input type="text" name="orderNum" id="orderNum" lay-verify="required"  autocomplete="off" placeholder="请输入排序码" class="layui-input">
                      </div>
               </div>
          <div class="layui-form-item">
                <div class="layui-input-block" style="text-align: right;">
                    <a class="layui-btn " lay-submit=""  lay-filter="doSubmit"><label class="layui-icon layui-icon-release"></label>提交</a>
                    <a class="layui-btn layui-btn-warm" onclick="javascript:$('#dataFrm')[0].reset()" lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>重置</a>
                </div>
           </div>
    </form>
</div>
<!--添加和修改的弹出层结束-->

<script src="/lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/lib/common/jquery.cookie.min.js" charset="utf-8"></script>
<script src="/lib/common/common.js" charset="utf-8"></script>
<script src="/lib/common/selectlayer.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'treeTable'], function () {
        var $ = layui.jquery;
        var treeTable = layui.treeTable;
        var form = layui.form;

        // 渲染表格
        var tableIns = treeTable.render({
            elem: '#menu-table',
            url: api + '/menu/loadMenuList',
            page: false,
            toolbar:"#toolBar",
            defaultToolbar: [],
            tree: {
                iconIndex: 1,  // 折叠图标显示在第几列
                isPidData: true,  // 是否是pid形式数据
                idName: 'id',  // 自定义id字段的名称
                pidName: 'pid',  // 自定义标识是否还有子节点的字段名称
                openName: 'spread'   // 自定义默认展开的字段名
            },
            cols: [[
                {type: 'numbers'},
                {field: 'title', title: '菜单名称'},
                {field: 'type',  title: '菜单位置', align: "center",width: 120,templet: function (d) {
                    if (d.type == 'topmenu') {
                        return '<span class="layui-badge layui-bg-red">顶部菜单</span>';
                    }
                    if (d.type == 'leftmenu') {
                        return '<span class="layui-badge layui-bg-blue">左侧菜单</span>';
                    }
                  }
				        },
                {field: 'typeCode', width: 120, title: '菜单编码'},
                {field: 'href', title: '页面路径'},
                {field: 'icon',  title: '菜单图标', align: "center",width: 120,templet:function(d){
                  var x="<i class='"+d.icon+"' ></i>";
                  return x;
                }},
                {field: 'target', title: '页面打开方式'},
                {templet: '#auth-state', width: 120, align: 'center', title: '操作'}
            ]],
            done: function () {
                layer.closeAll('loading');
            },
            parseData: function(res) {
                return {
                    "code": res.code == 200? 0 : res.code,
                    "data": res.data,
                    "msg": res.msg //解析提示文本
                };
            }
        });

        treeTable.on('toolbar(menu-table)', function(obj){
            switch(obj.event){
                case 'add':
                    openAddMenu();
                break;
            };
        });

        //监听工具条
        treeTable.on('tool(menu-table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'del') {
                deleteMenu(obj);
            } else if (layEvent === 'edit') {
                openUpdateMenu(data);
            }
        });

        var mainIndex;
        var url;  //动态的url
        var formState;
        function openAddMenu() {
            mainIndex=layer.open({
				type:1,
				title:'添加菜单',
				content:$("#addOrUpdateDiv"),
				area:['800px','530px'],
				success:function(index){
                    url=api + "/menu/addMenu";
                    formState = FORM_ADD;
					$("#dataFrm")[0].reset();
					//加载最大的排序码
					$.get(api + "/menu/getMaxOrderNum",function(res){
						$("#ordernum").val(res.data + 1);
					})
				}
			});	
        };

        function deleteMenu(obj) {
            $.ajax({
                url: api + '/menu/countChildMenuById',
                method: 'get',
                async: true,
                data: {'id':obj.data.id},
                success:function(resp){
                    if(resp.code === SUCCESS_CODE) {
                        if(resp.data > 0) {
                            layer.msg("该菜单有下属菜单，无法直接删除！");
                        } else {
                            layer.confirm('真的要删除菜单【'+obj.data.title+'】吗?', function (index) {
                                deleteMenuById(obj);
                                layer.close(index);
                            });
                        }
                    } else {
                        layer.msg("接口访问异常");
                    }
                },
                error:function(){
                    layer.msg("操作失败");
                }
            });
        };

        function deleteMenuById(obj) {
            $.ajax({
                url: api + '/menu/deleteById',
                method: 'delete',
                async: true,
                data: {'id':obj.data.id},
                success:function(resp){
                    layer.msg(resp.msg);
                    if(resp.code === SUCCESS_CODE) {
                        obj.del();
                    }
                },
                error:function(){
                    layer.msg("接口访问异常");
                }
            });
        };

        function openUpdateMenu(data) {
            mainIndex=layer.open({
				type:1,
				title:'更新菜单',
				content:$("#addOrUpdateDiv"),
				area:['800px','530px'],
				success:function(index){
                    url=api + "/menu/updateById";
                    formState = FORM_UPDATE;
                    $("#dataFrm")[0].reset();
                    if(data.pid==0){//说明是根节点
						$("#selectPid").hide();
					}else{
						$("#selectPid").show();
					}
                    form.val("dataFrm",data);
                    console.log(data);
                    $.get(api + '/menu/getById', {'id':data.pid}, function(resp){
                        $("#p_name").val(resp.data.title);
                    });
				}
			});	
        };

        form.on("submit(doSubmit)",function(data){
            $.ajax({
                url: url,
                method: formState === FORM_ADD? "post" : "put",
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(data.field),
                success:function(res){
                    layer.msg(res.msg);
                    tableIns.reload();
                },
                error:function(){
                    layer.msg("操作失败");
                }
            });
            layer.close(mainIndex);
            return false;
        });

        //监听启用操作
	     form.on('switch(enableSwitch)', function(obj){
            let param = {id: this.value, enable: obj.elem.checked? 1 : 0};
            $.ajax({
                url: api + "/menu/updateById",
                method: "put",
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(param),
                success:function(res){
                    layer.msg(res.msg);
                    tableIns.reload();
                },
                error:function(){
                    layer.msg("操作失败");
                }
            });
         });
         
         form.on('radio(typeFilter)', function(data){
            console.log(data.value); //被点击的radio的value值
            $(".item_topmenu").show();
            $(".item_leftmenu").show();
            $(".item_permission").show();
            if(data.value=='topmenu'){
                $(".item_leftmenu").hide();
                $(".item_permission").hide();
                $(".item_topmenu").show();
            }else if(data.value=='leftmenu'){
                $(".item_permission").hide();
                $(".item_topmenu").hide();
                $(".item_leftmenu").show();
            }else{
                $(".item_leftmenu").hide();
                $(".item_topmenu").hide();
                $(".item_permission").show();
            }
		});  

        //监听菜单选择的按钮事件打开菜单选择的弹出层
		$("#doSelectMenu").click(function(){
            var p_id=$("#p_id").val();
            var id=$("#id").val();
			openMenuSelecter(formState, id, p_id, function(id,name){
				// alert(id+"---"+name);
				$("#p_id").val(id);
				$("#p_name").val(name);
			});
		});
    });
</script>
<style>
    .p-container{
        display: flex;
        align-items: center;
    }
</style>
</body>
</html>